package com.hntxk.cqzd.common.service.Impl;

import com.hntxk.core.framework.service.impl.GenericServiceImpl;
import com.hntxk.core.util.StringUtil;
import com.hntxk.cqzd.common.model.FileModel;
import com.hntxk.cqzd.common.service.CommonFileService;
import com.hntxk.sp.dict.manager.DictManager;
import com.hntxk.sp.dict.model.Dict;
import com.hntxk.sp.util.LoginUserUtil;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service
public class CommonFileServiceImpl extends GenericServiceImpl implements CommonFileService {

    @Autowired
    protected HttpServletRequest request;
    /**
     *
      *
     * @param sql 对应mapper.xml中的某个方法
     * @param files 上传的文件
     * @param id //需要保存的文件对象外键id值  例如flupId
     * @return
     * @throws IOException
     */
    @Override
    public void upload(String sql, MultipartFile[] files, Long id,String sign) throws IOException {
        if (files.length>0){
            for(MultipartFile file:files){
                Calendar date2 = Calendar.getInstance();
                String rootDir="";
                if(sign!=null||sign!=""){
                    if("flup".equals(sign)){
                        Dict dictFlup = DictManager.getInstance().getDict("CQ_BASE_FILEPATH", "flup");
                        rootDir= dictFlup.getText();
                    }else if("dib".equals(sign)){
                        Dict dictDib = DictManager.getInstance().getDict("CQ_BASE_FILEPATH", "dib");
                        rootDir= dictDib.getText();
                    }else if("diac".equals(sign)){
                        Dict dictDiac = DictManager.getInstance().getDict("CQ_BASE_FILEPATH", "diac");
                        rootDir=dictDiac.getText();
                    }else{

                    }
                }
                String path=rootDir+date2.get(Calendar.YEAR)+"/"+(date2.get(Calendar.MONTH)+1)+"/"+date2.get(Calendar.DAY_OF_MONTH)+"/";
                System.out.println("path = " + path);

                String fileName = file.getOriginalFilename();
                Long size=file.getSize()/1024;
                String houzui = fileName.substring(fileName.lastIndexOf("."));
                File filepath = new File(path,fileName);
                if(!filepath.getParentFile().exists()){
                    filepath.getParentFile().mkdirs();
                }

                //创建文件对象 将主键和外键赋值
                FileModel fileModel=new FileModel();
                //设置文件类型
                fileModel.setContentType(file.getContentType());
                //设置文件代号
                UUID uuid= UUID.randomUUID();
                fileModel.setFileCode(uuid.toString());
                //设置外键值
                fileModel.setFkId(id);
                fileModel.setFileId((long) getPrimaryKey(fileModel));
                fileModel.setFileAddress(path+fileName);
                fileModel.setFileName(fileName);
                fileModel.setFileSize(size);
                fileModel.setFileExtension(houzui);
                fileModel.setFileDownloadNo((long) 0);
                fileModel.setFileUpTime(new Date());
                fileModel.setUpUserName(LoginUserUtil.getLoginUserName());
                fileModel.setUpUserId(LoginUserUtil.getLoginOperatorIdLong());
                //插入文件对象
                insert(sql,fileModel);
                file.transferTo(new File(path + File.separator + fileName));
              }
        }
    }

    /**
     * 下载文件方法
     * @param filePath  文件路径
     * @param fileName  文件名字
     * @return
     */
    @Override
    public ResponseEntity<byte[]> getFile(String filePath, String fileName) {
        File file=new File(filePath);
        try {
            //获得浏览器信息并转换为大写
            String agent = request.getHeader("User-Agent").toUpperCase();
            //IE浏览器和Edge浏览器，名称乱码
            if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO")>0 && agent.indexOf("RV:11")>0)) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {  //其他浏览器
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
        }catch (UnsupportedEncodingException e){
//            log.error("文件名转码异常，文件名：{}",fileName);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("fileName", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(FileUtil.readAsByteArray(file), headers,
                    HttpStatus.OK);
            return result;
        }catch (IOException e){
            throw new RuntimeException("文件不存在");
        }
    }

}
